package chapter3.eg2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Date;

public class TimeServerHandler extends SimpleChannelInboundHandler<String> {

  private static final String SEPARATOR = "\r\n";
  private int counter;

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    System.out.println("The time server receive order: " + msg + "; the counter is: " + ++counter);
    String currentTime = msg.equalsIgnoreCase("QUERY TIME ORDER")
      ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
    currentTime = currentTime + SEPARATOR;
    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.writeAndFlush(resp);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
  }
}
